<template>
  <div class="contractor-management">
    <div class="page-header">
      <h2>承包商管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增承包商
        </el-button>
      </div>
    </div>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>承包商列表</span>
          <div class="header-actions">
            <el-select
              v-model="filters.level"
              placeholder="资质等级"
              style="width: 120px"
              clearable
              @change="handleFilter"
            >
              <el-option label="A级" value="A" />
              <el-option label="B级" value="B" />
              <el-option label="C级" value="C" />
            </el-select>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索承包商名称"
              style="width: 200px"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table :data="filteredContractors" v-loading="loading">
        <el-table-column prop="name" label="承包商名称" width="200" />
        <el-table-column prop="code" label="承包商编码" width="150" />
        <el-table-column prop="contactPerson" label="联系人" width="120" />
        <el-table-column prop="contactPhone" label="联系电话" width="140" />
        <el-table-column prop="contactEmail" label="联系邮箱" width="180" />
        <el-table-column prop="qualificationLevel" label="资质等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.qualificationLevel)">
              {{ row.qualificationLevel }}级
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="businessScope" label="业务范围" min-width="200">
          <template #default="{ row }">
            <div class="business-scope">
              <el-tag
                v-for="scope in row.businessScope"
                :key="scope"
                size="small"
                class="scope-tag"
              >
                {{ scope }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 承包商表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑承包商' : '新增承包商'"
      width="800px"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="承包商名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入承包商名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="承包商编码" prop="code">
              <el-input v-model="formData.code" placeholder="请输入承包商编码" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="formData.contactPerson" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系邮箱" prop="contactEmail">
              <el-input v-model="formData.contactEmail" placeholder="请输入联系邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资质等级" prop="qualificationLevel">
              <el-select v-model="formData.qualificationLevel" placeholder="请选择资质等级">
                <el-option label="A级" value="A" />
                <el-option label="B级" value="B" />
                <el-option label="C级" value="C" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入承包商地址" />
        </el-form-item>
        
        <el-form-item label="业务范围" prop="businessScope">
          <div class="business-scope-input">
            <div
              v-for="(scope, index) in formData.businessScope"
              :key="index"
              class="scope-input-row"
            >
              <el-input
                v-model="formData.businessScope[index]"
                placeholder="请输入业务范围"
              />
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="removeBusinessScope(index)"
              />
            </div>
            <el-button
              type="primary"
              size="small"
              :icon="Plus"
              @click="addBusinessScope"
            >
              添加业务范围
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio value="active">启用</el-radio>
            <el-radio value="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleSubmit">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, Delete } from '@element-plus/icons-vue'
import { useContractorStore } from '@/stores/contractor'
import type { Contractor, ContractorForm } from '@/types'

const contractorStore = useContractorStore()

const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const searchKeyword = ref('')
const formRef = ref<FormInstance>()

const contractors = ref<Contractor[]>([])
const currentContractor = ref<Contractor | null>(null)

const filters = reactive({
  level: ''
})

const formData = reactive<ContractorForm>({
  name: '',
  code: '',
  contactPerson: '',
  contactPhone: '',
  contactEmail: '',
  address: '',
  qualificationLevel: 'C',
  businessScope: [''],
  status: 'active'
})

const formRules: FormRules = {
  name: [
    { required: true, message: '请输入承包商名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入承包商编码', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入联系邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  qualificationLevel: [
    { required: true, message: '请选择资质等级', trigger: 'change' }
  ]
}

// 过滤后的承包商列表
const filteredContractors = computed(() => {
  let result = contractors.value

  if (searchKeyword.value) {
    result = result.filter(contractor =>
      contractor.name.includes(searchKeyword.value)
    )
  }

  if (filters.level) {
    result = result.filter(contractor =>
      contractor.qualificationLevel === filters.level
    )
  }

  return result
})

// 获取资质等级标签类型
const getLevelTagType = (level: string) => {
  switch (level) {
    case 'A':
      return 'danger'
    case 'B':
      return 'warning'
    case 'C':
      return 'success'
    default:
      return 'info'
  }
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    contractors.value = await contractorStore.getAllContractors()
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  // 搜索逻辑在computed中处理
}

// 过滤
const handleFilter = () => {
  // 过滤逻辑在computed中处理
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  currentContractor.value = null
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: Contractor) => {
  isEdit.value = true
  currentContractor.value = row
  Object.assign(formData, {
    name: row.name,
    code: row.code,
    contactPerson: row.contactPerson,
    contactPhone: row.contactPhone,
    contactEmail: row.contactEmail,
    address: row.address,
    qualificationLevel: row.qualificationLevel,
    businessScope: [...row.businessScope],
    status: row.status
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: Contractor) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除承包商"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await contractorStore.deleteContractor(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 添加业务范围
const addBusinessScope = () => {
  formData.businessScope.push('')
}

// 删除业务范围
const removeBusinessScope = (index: number) => {
  if (formData.businessScope.length > 1) {
    formData.businessScope.splice(index, 1)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 过滤空的业务范围
    const validBusinessScope = formData.businessScope.filter(scope => scope.trim())
    
    if (isEdit.value && currentContractor.value) {
      await contractorStore.updateContractor(currentContractor.value.id, {
        ...formData,
        businessScope: validBusinessScope
      })
      ElMessage.success('更新成功')
    } else {
      await contractorStore.createContractor({
        ...formData,
        businessScope: validBusinessScope
      })
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    code: '',
    contactPerson: '',
    contactPhone: '',
    contactEmail: '',
    address: '',
    qualificationLevel: 'C',
    businessScope: [''],
    status: 'active'
  })
  formRef.value?.resetFields()
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.contractor-management {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 8px;
      }
    }
    
    .action-buttons {
      display: flex;
      gap: 8px;
    }
    
    .business-scope {
      .scope-tag {
        margin-right: 4px;
        margin-bottom: 4px;
      }
    }
  }
  
  .business-scope-input {
    .scope-input-row {
      display: flex;
      gap: 8px;
      margin-bottom: 8px;
      align-items: center;
      
      .el-input {
        flex: 1;
      }
    }
  }
}
</style>
